package dao.impl;

import dao.AdminDao;
import pojo.Admin;
import pojo.Manage;

import java.io.File;
import java.util.List;

public class AdminDaoImpl implements AdminDao {
    private List<Admin> userList = Manage.getUserList();

    public AdminDaoImpl(){
        File file = new File("saveData\\userData");
        if(!file.exists()){
            register("admin","admin");
        }
    }

    @Override
    public Admin login(String username, String passwd) {
        for(Admin admin: userList){
            if(admin.getUsername().equals(username) && admin.getPasswd().equals(passwd)){
                return admin;
            }
        }
        return null;
    }

    @Override
    public void register(String username, String passwd) {
        userList.add(new Admin(username,passwd));
        Manage.adminSaving(userList);
    }

    @Override
    public void update(String username, String newName, String newPasswd) {
        int userId = 0;
        for(Admin admin: userList){
            if(admin.getUsername().equals(username)){
                admin.setUsername(newName);
                admin.setPasswd(newPasswd);
                userList.set(userId,admin);
                break;
            }
            userId += 1;
        }
        Manage.adminSaving(userList);
    }

    @Override
    public void delete(String username) {
        for(Admin admin: userList){
            if(admin.getUsername().equals(username)){
                userList.remove(admin);
                break;
            }
        }
        Manage.adminSaving(userList);
    }
}
